package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.DefaultException;
import com.itheima.common.Paging;
import com.itheima.dto.UserLinkUserDto;
import com.itheima.entity.News;
import com.itheima.entity.UserLinkUser;
import com.itheima.mapper.NewsMapper;
import com.itheima.mapper.UserLinkUserMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.service.NewsService;
import com.itheima.service.UserLinkUserService;
import com.itheima.utils.CheckUtil;
import com.itheima.utils.PageUtils;
import com.itheima.vo.news.NewsLastVo;
import com.itheima.vo.userLinkUser.UserLinkUserFindVo;
import com.itheima.vo.userLinkUser.UserLinkUserVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 51585
 * @description 针对表【user_link_user】的数据库操作Service实现
 * @createDate 2022-10-26 09:55:02
 */
@Service
public class UserLinkUserServiceImpl extends ServiceImpl<UserLinkUserMapper, UserLinkUser>
        implements UserLinkUserService {

    @Resource
    private UserLinkUserMapper userLinkUserMapper;
    @Resource
    private NewsMapper newsMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private NewsService newsService;

    @Override
    public List<UserLinkUserVo> showChats(String keyword) throws Exception {
        String userId = CheckUtil.checkLogin();
//        String userId = "19251104252";
        List<UserLinkUserVo> list = userLinkUserMapper.showChats(userId, keyword);
        // 补充最新聊天内容
        list.forEach(k -> {
            NewsLastVo last = newsMapper.findLast(userId, k.getUserId());
            News news = newsService.lambdaQuery()
                    .select(News::getReadStatus)
                    .eq(News::getSendId, k.getUserId())
                    .eq(News::getAcceptId, userId)
                    .isNull(News::getDeletedAt)
                    .orderByDesc(News::getSendTime)
                    .last("limit 1").one();
            Optional.ofNullable(last).ifPresent(mid -> {
                k.setContent(mid.getContent());
                k.setSendTime(mid.getSendTime());
                Integer num = userLinkUserMapper.findUnreadRecords(k.getUserId(), userId);
                k.setUnreadRecords(Optional.ofNullable(num).orElse(0));
            });
            if (Objects.isNull(news)) {
                k.setReadStatus(1);
            }else {
                k.setReadStatus(news.getReadStatus());
            }
        });
        List<UserLinkUserVo> collect = list
                .stream().sorted(Comparator.comparing(UserLinkUserVo::getTopStatus, Comparator.reverseOrder())
                        .thenComparing(UserLinkUserVo::getSendTime, Comparator.reverseOrder()))
                .collect(Collectors.toList());
        return collect;
    }

    @Override
    public Paging<UserLinkUserFindVo> findUser(UserLinkUserDto userLinkUserDto) throws Exception {
        String userId = CheckUtil.checkLogin();
        Page<?> page = new Page<>(userLinkUserDto.getPageIndex(), userLinkUserDto.getPageSize());
        IPage<UserLinkUserFindVo> iPage = userMapper.findUser(page, userId, userLinkUserDto);
        iPage.getRecords().forEach(vo -> {
            NewsLastVo last = newsMapper.findLast(userId, vo.getUserId());
            News news = newsService.lambdaQuery()
                    .select(News::getReadStatus)
                    .eq(News::getSendId, vo.getUserId())
                    .eq(News::getAcceptId, userId)
                    .isNull(News::getDeletedAt)
                    .orderByDesc(News::getSendTime)
                    .last("limit 1").one();
            Optional.ofNullable(last).ifPresent(k -> {
                vo.setContent(k.getContent());
                vo.setSendTime(k.getSendTime());
            });
            if (Objects.isNull(news)) {
                vo.setReadStatus(1);
            }else {
                vo.setReadStatus(news.getReadStatus());
            }
        });
        return PageUtils.toPage(iPage);
    }

    @Override
    public void topUser(String userId) throws Exception {
        String currentUserId = CheckUtil.checkLogin();
        UserLinkUser one = this.lambdaQuery()
                .eq(UserLinkUser::getUserAid, currentUserId)
                .eq(UserLinkUser::getUserBid, userId)
                .one();
        Optional.ofNullable(one).orElseThrow(()->new DefaultException("没有当前聊天"));
        if (one.getTopStatus() == 1) {
            throw new DefaultException("已置顶，请勿重复进行");
        }
        one.setTopStatus(1);
        this.updateById(one);
    }

    @Override
    public void cancelTopUser(String userId) throws Exception {
        String currentUserId = CheckUtil.checkLogin();
        UserLinkUser one = this.lambdaQuery()
                .eq(UserLinkUser::getUserAid, currentUserId)
                .eq(UserLinkUser::getUserBid, userId)
                .one();
        Optional.ofNullable(one).orElseThrow(()->new DefaultException("没有当前聊天"));
        if (one.getTopStatus() == 0) {
            throw new DefaultException("未置顶，请勿重复进行");
        }
        one.setTopStatus(0);
        this.updateById(one);
    }

}




